package com.pxmeta.user.converter;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.common.collect.Lists;
import com.pxmeta.user.entity.User;
import com.pxmeta.user.entity.dto.UserDTO;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.mapstruct.Mapper;
import org.springframework.beans.BeanUtils;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

//@Mapper(componentModel = "spring")
public class UserConverter {

    public static UserDTO toDto(User user){
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(user,dto);

        LocalDate birthday = dto.getBirthday();
        if (ObjectUtil.isNotNull(birthday)) {
            LocalDate now = LocalDate.now();
            int nowYear = now.getYear();
            int birthdayYear = birthday.getYear();
            int age = nowYear - birthdayYear;
            dto.setAge(age);
        }
        return dto;
    }

    public static List<UserDTO> toDtoList(List<User> users){
        if (CollectionUtil.isEmpty(users)){
            return new ArrayList<>();
        }
        LinkedList<UserDTO> list = Lists.newLinkedList();
        for (User user : users) {
            UserDTO dto = new UserDTO();
            BeanUtils.copyProperties(user,dto);
            list.add(dto);
        }
        for (UserDTO userDTO : list) {
            LocalDate birthday = userDTO.getBirthday();
            if (ObjectUtil.isNotNull(birthday)) {
                LocalDate now = LocalDate.now();
                int nowYear = now.getYear();
                int birthdayYear = birthday.getYear();
                int age = nowYear - birthdayYear;
                userDTO.setAge(age);
            }
        }
        return list;
    }

}
